// pages/ordersNew/ordersNew.js
import WxValidate from '../../utils/WxValidate.js'
import { formatTime} from '../../utils/util.js'

const app = getApp()

let Validate = ""
let input_date;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    array: ['选择品牌商' , '1','2'],
    index: -1,
    materialsIndex: -1,
    regionIndex: -1,
    storeIndex: -1,
    customItem: '全部',
    region: ['请选择', '请选择', '请选择'],
    materials: wx.getStorageSync('materials'),
    time: '请选择时间',
    pres: [],
    clue_id: undefined,
    measure: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  getPres(){
    app.query('/api/pres', {}, 'get').then(res => {
      // console.log(res)
      if (res.status == 'success') {
        // console.log(res.select_companies[0].stores_tree[0].children[-1])
        this.setData({
          pres: res.select_companies
        })
      }else{
        app.showToast(error.msg, false, 500, '../../assets/warning.png')
      }
    });
  },
  measureLink(){
    wx.navigateTo({
      url: '../measure/measure'
    })
  },
  onLoad: function (options) {
    console.log(options)
    input_date = formatTime(new Date(), 1);
    this.getPres();
    const rules = {
      name: {
        required: true
      },
      mobile: {
        required: true,
        tel: true
      },
      introducer_tel: {
        tel: true
      },
      address: {
        required: true
      },
      estimated_total: {
        required: true
      },
      expected_square: {
        required: true
      },
      total: {
        required: true
      }
    }

    const messages = {
      name: {
        required: '请输入姓名'
      },
      introducer_tel: {
        tel: '介绍人号码格式错误'
      },
      mobile: {
        required: '请输入手机号码',
        tel: '手机格式错误'
      },
      address: {
        required: '请输入地址',
      },
      estimated_total: {
        required: '请输入预估产品价格'
      },
      expected_square: {
        required: '请输入预估面积'
      },
      total: {
        required: '请输入服务费'
      }
    }
    Validate = new WxValidate(rules, messages)
    // if(!!options.title){
    wx.setStorageSync('measure','')
    this.setData({ 
      options: !options.title ? false : JSON.parse(options.title),
      cgj_id: wx.getStorageSync('current_user').cgj_user_id,
      materials: wx.getStorageSync('materials'),
      input_date: input_date
    })
    // }
  },
  bindMaterials(e){
    this.setData({
      materialsIndex: e.detail.value
    })
  },
  bindRegions(e){
    // const { storeIndex, regionIndex , pres , index} =this.data
    // console.log(e)
    this.setData({
      regionIndex: e.detail.value
    })
    // console.log(pres[index].stores_tree)
  },
  bindStores(e) {
    this.setData({
      storeIndex: e.detail.value
    })
  },
  bindPickerChange(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })
  },
  bindTimeChange (e) {
    console.log(new Date(e))
    this.setData({
      time: e.detail.value
    })
  },
  bindRegionChange(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region: e.detail.value
    })
  },
  handleSwitch(e){
    console.log(e)
    const { cgj_id } = this.data;
    if (cgj_id == 'null' || cgj_id == null && e.detail.value){
      app.showModel({ title: '授权窗管家', msg: '授权窗管家访问你的账号'}).then(res => {
        if(res){
          app.query('/api/auth/cgj' ,{} , 'get').then(res => {
            app.showToast('授权成功', 'success', 500)
            wx.setStorageSync('current_user', res.current_user)
            this.setData({
              cgj_id: wx.getStorageSync('current_user').cgj_user_id,
            })
          })
         
        }else{
        // app.showToast('请选择师傅', false, 500, '../../assets/warning.png')
        }
      })
    }
  },
  formSubmit(e) {
    // wx.navigateTo({
    //   url: '../reaspon/reaspon?title=orders'
    // })
    const params = e.detail.value
    const { pres, materials, index, materialsIndex, regionIndex, storeIndex, region, time, clue_id} = this.data;
    if (!Validate.checkForm(e)) {
      const error = Validate.errorList[0]
      app.showToast(error.msg, false, 500, '../../assets/warning.png')
      //提示信息  
      console.log(error, e)
      return false
    }
    if (index === -1 || materialsIndex === -1 || regionIndex === -1){
      app.showToast('请填完必填项', false, 500, '../../assets/warning.png')
      return false
    } else if (region[2] === '请选择' ||region[2] === '全部' || time === '请选择时间'){
      app.showToast('请填完必填项', false, 500, '../../assets/warning.png')
      return false
    } 
    // else if ( !wx.getStorageSync('measure').name ){
    //   app.showToast('请选择师傅', false, 500, '../../assets/warning.png')
    //   return false
    // }
    app.query('/api/orders', {
      'id': clue_id || null,
      remark: params.remark,
      customer: { name: params.name, tel: params.mobile,province: region[0], city: region[1], area: region[2], street: params.address},
      order: { expected_square: params.expected_square,
       total: params.total, 
       booking_date: time, 
       cgj_customer_service_id: wx.getStorageSync('measure').id || '', 
       measure_master: wx.getStorageSync('measure').name || '', 
       cgj_company_id: pres[index].cgj_id, 
       material: materials[materialsIndex].name, 
       material_id: materials[materialsIndex].id, 
       introducer_name: params.introducer_name, 
       introducer_tel: params.introducer_tel, 
       region_id: pres[index].stores_tree[regionIndex].id, 
       estimated_total: params.estimated_total, 
       store_id: storeIndex == -1 ? null : pres[index].stores_tree[regionIndex].children[storeIndex].id,
       is_sync: params.switch
       }
    }, 'post').then(res => {
        console.log(res)
      if(res.status==='success'){
        wx.navigateTo({
          url: '../reaspon/reaspon?title=orders'
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      measure: wx.getStorageSync('measure'),
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    wx.removeStorageSync('measure')
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})